package com.situ.admin.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.admin.bean.APIResult;
import com.situ.admin.bean.Root;
import com.situ.admin.service.RootService;
import com.situ.admin.utils.TokenUtil;
import com.situ.admin.utils.TokenUtil.Token;

/**
 * 
 * @author: JavaSiegeLoin(Gang)
 * @E-mail: wzg15653@163.com
 * @创建日期: 2021年10月14日 下午3:20:14
 * @ClassName: RootInterceptor
 * @类描述-Description:拦截器
 */

@Component // 组件
public class RootInterceptor implements HandlerInterceptor {

	@Autowired
	private RootService rootService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		// 1获取客户端传递过来的token
		String strToken = request.getHeader("token");
		if (strToken == null || strToken.length() == 0) {
			// 用户没有登录
			setResponse(response, "用户未登录！！请登陆后再进行操作！！");
			// 拦截
			return false;
		}
		// 2解密Token，时间有没有过期
		Token token = TokenUtil.parseToken(strToken);
		if (token.getStatus() == 1) {
			setResponse(response, "登录已过期！！请重新登陆！！");
			return false;
		}
		// 3是不是一个有效的用户
		String rootname = token.getCode();
		Root root = rootService.getByRootName(rootname);
		if (root == null) {
			setResponse(response, "当前的用户不是一个有效的用户，请重新登陆！！");
			return false;
		}

		// 4禁用
		if (root.getStatus() == 1) {
			setResponse(response, "用户已被禁用，请联系管理员");
			return false;
		}

		// 5刷新token 重置有效时间
		strToken = TokenUtil.createToken(token.getCode());
		response.setHeader("token", strToken);
		return true;
	}

	private void setResponse(HttpServletResponse response, String msg) throws IOException {
		APIResult apiResult = APIResult.unauthorized(msg);

		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(apiResult);
		response.setContentType("application/json; charset=utf-8");
		response.getWriter().write(json);
	}

}
